<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;
use Session;
use App\Models\UserRole;
class User extends Model
{
    protected $table='user';
    protected $guarded=[];

    /*
     * 用户角色表关联关系
     * */
    public function roles()
    {
        return $this->belongsToMany('App\Models\Role','user_role','user_id','role_id');
    }

    //保存新建用户
    public static function checkUser($request){
        $request->validate(['username'=>'required|between:6,20|unique:user,username',
            'password'=>'required|between:6,18|confirmed',
            //'cellphone'=>'required|between:11,11|unique:user,cellphone'
        ]);
        $data['username']=$request->username;
        $data['realname']=$request->realname;
        $data['cellphone']=$request->cellphone;
        $password=$request->password;
        $data['password']=$data['password']=Hash::make($password);
        $newUser=User::create($data);
        if($newUser){
            return redirect()->back()->with('status','小主！添加成功！');
        }else{
            $request->session()->flash('username', "$request->username");
            $request->session()->flash('realname', "$request->realname");
            $request->session()->flash('cellphone', "$request->cellphone");
            $request->session()->flash('password', "$request->password");
            $request->session()->flash('confirm_password', "$request->confirm_password");
            return redirect()->back()->with('status','小主！添加失败!');
        }

    }

    /*
     * 编辑用户
     * */
    public static function updateUser($request){
        $data['cellphone']=$request->cellphone;
        $data['realname']=$request->realname;
        if($request->has('password') && $request->password!=null && $request->password==$request->password_confirmation){
            $password=$request->password;
            $data['password']=$data['password']=Hash::make($password);
        }

        $updateUser=User::where('id',$request->userId)->update($data);
        if($updateUser){
            return  back()->with('status','修改成功');
        }else{
            return  back()->with('status','用户信息未做任何修改');
        }
    }



    //保存添加权限
    public static function checkRole($request){
        $data['role_id']=$request->roleId;
        $data['user_id']=$request->userId;
        UserRole::firstOrCreate($data);
        return redirect()->back()->with('status','小主！添加成功！');

    }


}
